<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClickTab">
      <el-tab-pane label="全部" name="0"></el-tab-pane>
      <el-tab-pane label="短视频素材" name="1"></el-tab-pane>
      <!--    <el-tab-pane label="上新" name="2"></el-tab-pane>-->
      <el-tab-pane label="图片素材" name="3"></el-tab-pane><!--之前叫‘种草’-->
      <!--        <el-tab-pane label="买家秀" name="4"></el-tab-pane>-->
    </el-tabs>
    <div class="filter-container">
      <!--      <el-input v-model.number="listQuery.walkMemberUid" clearable placeholder="创作号" style="width: 200px;" class="filter-item" @keyup.enter.native="getList()" />-->
      <!-- <el-select v-model="listQuery.type" placeholder="类型" class="filter-item" clearable filterable>
          <el-option
            v-for="item in typeOptions"
            :key="item.key"
            :label="item.text"
            :value="item.key">
          </el-option>
        </el-select> -->
      <el-select v-model="listQuery.status" placeholder="状态" class="filter-item" clearable filterable>
        <el-option
          v-for="item in statusOptions"
          :key="item.key"
          :label="item.text"
          :value="item.key"
        >
        </el-option>
      </el-select>
      <el-select v-model="listQuery.shopId" placeholder="所属店铺" class="filter-item" clearable filterable>
        <el-option
          v-for="item in shopOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="listQuery.source" placeholder="来源" class="filter-item" clearable filterable>
        <el-option
          v-for="item in sourceOptions"
          :key="item.key"
          :label="item.text"
          :value="item.key"
        >
        </el-option>
      </el-select>
      <el-date-picker class="filter-item" v-model="listQuery.startTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间" />
      -
      <el-date-picker  class="filter-item"  v-model="listQuery.endTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间" />
      <el-select @change="handleSelect" v-model="listQuery.walkMemberId" placeholder="所属会员"
                 class="filter-item" clearable filterable>
        <el-option
          v-for="item in downloadWalkMemberOptions"
          :key="item.id+''"
          :label="item.nickname"
          :value="item.id+''"
        >
        </el-option>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" circle @click="getList"></el-button>
      <!--      <br>-->
      <!--			<el-button-group>-->
      <!--			<el-button class="filter-item" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete">删除</el-button>-->
      <!--			</el-button-group>-->
    </div>
    <el-table
      :key="tableKey"

      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <!--      <el-table-column label="ID" prop="id" align="center" width="65">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ scope.row.walkTrendsDownloadNum.id }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="所属商家" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.umsShop.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="适用商品" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.pmsGoods">{{ scope.row.pmsGoods.title }}</span>
          <span v-else>所有商品</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="100px"  align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.walkTrendsDownloadNum.type == 1" style="color: #C03639;">{{ scope.row.walkTrendsDownloadNum.type | typeFilter}}</span>
          <span v-if="scope.row.walkTrendsDownloadNum.type == 2" style="color: #00bcbc;">{{ scope.row.walkTrendsDownloadNum.type | typeFilter}}</span>
          <span v-if="scope.row.walkTrendsDownloadNum.type == 3" style="color: #c885c8;">{{ scope.row.walkTrendsDownloadNum.type | typeFilter}}</span>
          <span v-if="scope.row.walkTrendsDownloadNum.type == 4" style="color: #00cb00;">{{ scope.row.walkTrendsDownloadNum.type | typeFilter}}</span>
        </template>
      </el-table-column>

      <el-table-column label="来源" width="100px"  align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.walkTrendsDownloadNum.source == 1" style="color: #3659c0;">{{ scope.row.walkTrendsDownloadNum.source | sourceFilter}}</span>
          <span v-if="scope.row.walkTrendsDownloadNum.source == 2" style="color: #00bcbc;">{{ scope.row.walkTrendsDownloadNum.source | sourceFilter}}</span>

        </template>
      </el-table-column>
      <el-table-column label="申请/赠送人" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.walkTrendsDownloadNum.downloadWalkMemberName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请/赠送时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.walkTrendsDownloadNum.addTime|parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.walkTrendsDownloadNum.status == 1 ? 'success' : 'danger' ">
            {{ scope.row.walkTrendsDownloadNum.status | statusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" class-name="small-padding" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-button-group>
            <el-tooltip class="item" effect="dark" content="查看商品" placement="top" v-if="scope.row.pmsGoods">
              <el-button type="primary" icon="el-icon-s-promotion" size="mini" @click="handleViewTrends(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="审核" placement="top">
              <el-button v-if="scope.row.walkTrendsDownloadNum.status == 0" type="primary" icon="el-icon-circle-check" size="mini" @click="handleVerify(scope.row.walkTrendsDownloadNum)"></el-button>
            </el-tooltip>
          </el-button-group>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize"
                @pagination="getList"
    />


    <!--查看详情-->
    <el-dialog title="查看" :visible.sync="dialogViewVisible" :destroy-on-close="true">
      <div class="flex">
        <el-image
          class="flex f-s-0 margin-r8"
          style="height: 40px"
          :src="trendsDetail.downloadWalkMemberHeadImg"
        >
        </el-image>
        <div class="flex f-c">
          <span class="link-type" style="font-size: 12px;">{{ trendsDetail.walkMemberName }}</span>
          <span class="tips-class margin-t6">申请/赠送人: {{ trendsDetail.downloadWalkMemberName }}</span>
        </div>
        <div class="flex f-j-e flex-1">
          <span class="tips-class" style="float: right;">申请/赠送时间：{{ trendsDetail.addTime | parseTime }}</span>
        </div>
      </div>

      <div>
        适用商品：<p v-text="trendsGoodsDetail.title" style="white-space: pre-wrap; font-size: 13px; padding: 10px;"></p>
       <p v-if="trendsGoodsDetail.mainImg">
         商品主图： <el-image
            v-for="(item,index) in trendsGoodsDetail.mainImg.split('|')"
            :key="index"
            style="width: 30%;margin-left: 5px;border-radius: 5px;"
            :src="item"
            :preview-src-list="trendsGoodsDetail.mainImg.split('|')"
          >
          </el-image>
        </p>
       <p v-if="trendsGoodsDetail.mainVideo">
         商品视频： <video id="playVideos" width="10%" height="10%" webkit-playsinline="true" preload="auto" controls="controls">
            <source :src="trendsGoodsDetail.mainVideo" type="video/mp4">
          </video>
        </p>
      </div>

    </el-dialog>
    <!--审核框-->
    <el-dialog title="审核" :visible.sync="dialogVerifyVisible">
      <el-form ref="verifyForm" :model="verifyForm" label-width="80px" label-position="right">
        <el-form-item label="审核结果" prop="status" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
          <el-radio-group v-model="verifyForm.status">
            <el-radio :label="1" border>通过</el-radio>
            <el-radio :label="2" border>不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider>拒绝原因</el-divider>
        <el-form-item label="拒绝原因" prop="reasonCheck">
          <el-select v-model="verifyForm.reasonCheck" placeholder="请选择" style="width: 100%;" @change="$set(verifyForm,'reason',verifyForm.reasonCheck);" clearable >
            <el-option
              key="0"
              value="内容违规"
              label="内容违规">
            </el-option>
            <el-option
              key="1"
              value="涉及黄色"
              label="涉及黄色">
            </el-option>
            <el-option
              key="2"
              value="涉嫌广告"
              label="涉嫌广告">
            </el-option>
            <el-option
              key="10"
              value="其他"
              label="其他">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="填写原因" prop="reason">
          <el-input type="textarea" v-model="verifyForm.reason" placeholder="请输入拒绝理由" :rows="6"/>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVerifyVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmVerify">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.tips-class {
  font-size: 12px;
  color: #999;
}

.comment-item {
  padding: 20px;
  border-radius: 5px;
  background-color: #f9f9f9;
  margin-bottom: 12px;
}

.comment .sub-item {
  padding: 10px;
  background-color: #e8ecef;
  border-radius: 5px;
  margin-top: 5px;
  margin-left: 34px;
}
</style>

<script>
import {
  getTrendsList,
  publishTrends,
  deleteTrends,
  getCommentList,
  getTrendsDownloadNumApply,
  verifyTrendsDownloadNum,
  getDownloadWalkMemberSelector
} from '@/api/trends'
import { getGoodsList } from '@/api/goods'
import waves from '@/directive/waves' // Waves directive
import { parseTime, renderTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import ImageSource from '@/components/Upload/imageSource'
import MultipleUpload from '@/components/Upload/multipleImage'
import SingleVideoUpload from '@/components/Upload/singleVideo'
import {getShopSelector} from "@/api/shop";

const typeOptions = [
  { key: 1, text: '短视频' },
  { key: 2, text: '上新' },
  { key: 3, text: '图片' }
  /* { key: 4, text: '买家秀' }, */
]
const sourceOptions = [
  { key: 1, text: '认证赠送' },
  { key: 2, text: '提交申请' },

]
// arr to obj ,such as { CN : "China", US : "USA" }
const typeKeyValue = typeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.text
  return acc
}, {})
const sourceKeyValue = sourceOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.text
  return acc
}, {})
const statusOptions = [
  { key: 0, text: '待审核' },
  { key: 1, text: '审核通过' },
  { key: 2, text: '不通过' },
  { key: 3, text: '已撤回' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const statusKeyValue = statusOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.text
  return acc
}, {})

export default {
  name: 'trendsList',
  components: {
    Pagination, ImageSource,
    MultipleUpload,
    SingleVideoUpload
  },
  directives: { waves },
  filters: {
    sourceFilter(source){
      return sourceKeyValue[source]
    },
    typeFilter(status) {
      return typeKeyValue[status]
    },
    statusFilter(type) {
      return statusKeyValue[type]
    }
  },
  data() {
    return {
      downloadWalkMemberOptions: [],
      shopOptions:[],
      verifyForm: {},
      dialogVerifyVisible:false,
      props: { label: 'name', value: 'id', children: 'children', checkStrictly: true, multiple: true },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      trendsForm: {},
      dialogFormVisible: false,
      dialogVideoVisible: false,
      dialogViewVisible: false,
      dialogCommentVisible: false,
      dialogType: '',
      multipleSelection: [],
      typeOptions,
      statusOptions,
      sourceOptions,
      activeName: '0',
      goodsOptions: [],
      videoUrl: '',
      trendsDetail: {},
      trendsGoodsDetail: {},
      commentList: [],
      commentTotal: 0,
      commentListLoading: true,
      commentListQuery: {
        page: 1,
        pageSize: 20
      },
      activeNames: []
    }
  },
  created() {
    this.getDownloadWalkMemberOptions()
    const downloadWalkMemberId = this.$route.query && this.$route.query.downloadWalkMemberId
    if (downloadWalkMemberId) {
      this.listQuery.walkMemberId = downloadWalkMemberId;
    }
    this.getList()
    this.getShopList()
  },
  methods: {
    getShopList() {
      getShopSelector().then(response => {
        this.shopOptions = response.data
      })
    },
    confirmVerify() {
      this.$refs['verifyForm'].validate((valid) => {
        if (valid) {
          let formData ={
            id: this.verifyForm.id,
            status: this.verifyForm.status,
            reason: this.verifyForm.reason
          }
          verifyTrendsDownloadNum(formData).then((response) => {
            this.getList()
            this.dialogVerifyVisible = false
            this.$notify({
              title: '成功',
              message: '审核成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleVerify(row) {
      let id = ''
      if(row && row.id){
        id = row.id
      }else{
        const verVals = this.multipleSelection;
        if(!verVals || verVals.length <= 0){
          this.$message({
            message: '请至少选择一条数据',
            type: 'error',
            duration: 2000
          })
          return;
        }
        let values = [];
        verVals.forEach(val =>{
          values.push(val.id);
        })
        id = values.join(",")
      }
      this.verifyForm = {status:1, id: id}// copy obj
      this.dialogVerifyVisible = true
      this.$nextTick(() => {
        this.$refs['verifyForm'].clearValidate()
      })
    },
    getGoodsSelector() {
      getGoodsList({ page: 1, pageSize: 999 }).then(response => {
        this.goodsOptions = response.data.list
      })
    },
    getList() {
      this.listLoading = true
      this.listQuery.dateFrom = renderTime(this.listQuery.startTime)
      this.listQuery.dateTo = renderTime(this.listQuery.endTime)
      getTrendsDownloadNumApply(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleCreate() {
      this.trendsForm = {}
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.getGoodsSelector()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let formData = Object.assign({}, this.trendsForm)
          formData.addTime = null
          formData.updTime = null
          console.log(formData.goodsId)
          // if(formData.goodsId){
          //   formData.goodsIds = formData.goodsId.join(",")
          // }

          formData.goodsIds = formData.goodsId
          publishTrends(formData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '发布成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete() {
      const delVals = this.multipleSelection
      if (!delVals || delVals.length <= 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'error',
          duration: 2000
        })
        return
      }
      this.$confirm('您确定要删除这些记录?', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let values = []
        delVals.forEach(val => {
          values.push(val.walkTrends.id)
        })
        deleteTrends(values.join(',')).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
        .catch(err => {
          console.error(err)
        })
    },
    handleClickTab(tab, event) {
      this.listQuery.page = 1
      this.listQuery.pageSize = 20
      this.activeName = tab.name
      this.listQuery.type = this.activeName == '0' ? null : this.activeName
      this.getList()
    },
    viewVideo(row) {
      this.videoUrl = ''
      this.videoUrl = row.videoUrl
      this.dialogVideoVisible = true
      document.getElementById('playVideos').src = row.videoUrl
    },
    closeVideoDialog() {
      document.getElementById('playVideos').src = ''
      this.dialogVideoVisible = false
    },
    handleViewTrends(row) {
      this.trendsDetail = row.walkTrendsDownloadNum
      this.trendsGoodsDetail = row.pmsGoods
      this.dialogViewVisible = true
    },
    handleViewComment(trendsId) {
      this.commentListQuery.trendsId = trendsId
      this.getCommentList()
      this.dialogCommentVisible = true
    },
    getCommentList() {
      getCommentList(this.commentListQuery).then(response => {
        this.commentList = response.data.list
        this.commentTotal = response.data.total
        this.commentListLoading = false
      })
    },
    getDownloadWalkMemberOptions() {
      getDownloadWalkMemberSelector().then(response => {
        this.downloadWalkMemberOptions = response.data
      })
    },
    handleSelect() {
      this.$forceUpdate()
    },
  }
}
</script>

<style lang="scss" scoped>

.el-radio {
  margin-right: 0px !important;
}

.el-select-dropdown {
  span {
    white-space: pre !important;
  }
}

.el-select-dropdown__item {
  white-space: pre !important;
}

</style>
